<template>
	<view class="user-list">
		<view class="header-box">
			<uni-easyinput prefixIcon="search" v-model="searchVal" @clear="searchEvent" primaryColor="#ffd589"
				placeholder="请输入用户昵称或手机号"></uni-easyinput>
			<view class="search-btn">
				<view class="btn" @click="searchEvent">搜索</view>
			</view>
		</view>
		<scroll-view scroll-y class="scroll-box" @scrolltolower="getDataEvent">
			<view class="main">
				<view class="card-box" v-for="(item,index) in listData" :key="index" @click="toUserDetail(item)">
					<image class="user-img" src="@/static/main-icon/user.png" mode=""></image>
					<view style="flex: 1;">
						<view>
							<view class="card-title">{{item.nickname}}(<text v-if="item.userType === 0">普通</text> <text
									v-if="item.userType === 1">VIP</text>)</view>
						</view>
						<view class="card-text flex-box">
							<view class="mr-box">角色：{{item.userType===0?'普通用户':'VIP'}}</view>
							<view class="mr-box">余额：¥ {{item.balance}}</view>
							<view class="mr-box">积分：{{item.score}}</view>
						</view>
						<view @click="callNumber(item)" class="card-text">电话：<uni-icons class="phone-icon" type="phone"
								color="#ff9600" size="16"></uni-icons>{{item.mobile || '- -'}} </view>
						<view class="card-text flex-sb">
							<view>预定次数：{{item.orderCount}}</view>
							<view class="flex" v-if="!isCheck">
								<view class="common-btn" @click.stop="openPop('1',item)">储值卡</view>
								<view class="common-btn" @click.stop="openPop('2',item)">赠送</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="noMore">暂无更多</view>
		</scroll-view>
		<uni-popup ref="popup" type="bottom" :safe-area='false'>
			<view class="pop-box">
				<view class="pop-title">{{type==='1'?'设置储值卡金额':'赠送时长卡'}}</view>
				<view class="pop-content" v-if="type==='1'">
					<view class="pop-item">
						<view class="pop-item-title-long">用户：</view>
						<view>{{currentConfig.nickname}}</view>
					</view>
					<view class="pop-item">
						<view class="pop-item-title-long">本门店储值卡金额：</view>
						<view>￥{{currentConfig.balance}}</view>
					</view>
					<view class="pop-item">
						<view class="pop-item-title-long">设置储值卡金额为：</view>
						<uni-easyinput class="pop-input" type="number" :maxlength="10" primaryColor="#ffd589" trim="all"
							v-model="currentConfig.balance" placeholder="请输入金额"></uni-easyinput>元
					</view>
				</view>
				<view class="pop-content" v-else>
					<view class="pop-item">
						<view class="pop-item-title">用户：</view>
						<view>{{currentConfig.nickname}}</view>
					</view>
					<view class="pop-item flex-sb">
						<view class="pop-item-title">赠送时长卡</view>
						<view>共计：{{allCount}}张</view>
					</view>
					<view class="time-card-box">
						<view class="time-card" v-for="(item,index) in timeCardList" :key="index">
							<view class="time-card-item">{{item.timeCardName}}</view>
							<view class="time-card-item flex-sb">
								<view>时长：{{item.hour}}小时</view>
								<view>
									<uni-number-box v-model="item.count" :max="10"
										@change="(val)=>changeCount(val,item)" />
								</view>
							</view>
							<view class="time-card-item">金额：￥{{item.price}}</view>
							<view class="time-card-item" v-if="item.expType === '1'">有效期：{{item.expStartTime}} ~ {{item.expEndTime}}</view>
							<view class="time-card-item" v-else>有效期：获得卡后{{item.expDay}}天 </view>
						</view>
					</view>

				</view>
				<view class="pop-btn-box">
					<view class="cancel-btn" @click="closePop">取消</view>
					<view class="submit-btn" @click="submitEvent">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchVal: '',
				listData: [],
				shopId: '',
				totalTime: 0,
				pageSize: 10,
				pageNum: 1,
				total: 0,
				currentConfig: {},
				type: '',
				timeCardList: [],
				allCount:'0',
				isCheck:false // 是否是选择用户
			};
		},
		methods: {
			// 跳转用户详情
			toUserDetail(item){
				if(this.isCheck){
					const eventChannel = this.getOpenerEventChannel()
					eventChannel.emit('reload', {
						userName: item.nickname,
						userId:item.userId
					})
					uni.navigateBack()
				}else{
					uni.navigateTo({
						url:`/pages/user-detail/user-detail?userId=${item.userId}&shopId=${this.shopId}`
					})
				}
			},
			// 选择时长卡数量
			changeCount(val, item) {
				this.$nextTick(() => {
					let sum = 0
					this.timeCardList.forEach((item) => {
						sum += item.count
					})
					this.allCount = sum
				})
			},
			// 打开弹窗
			openPop(type, item) {
				this.type = type
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.currentConfig = JSON.parse(JSON.stringify(item));
				if (type === '2') {
					this.currentConfig.allCount = 0
				}
				this.$refs.popup.open('center')
			},
			closePop() {
				this.$refs.popup.close()
			},
			// 弹窗确认事件
			submitEvent() {
				if (this.type === '1') {
					this.saveBlance()
				}else{
					this.sendCard()
				}
			},
			// 更新余额
			saveBlance() {
				if (this.currentConfig.balance === '') {
					uni.showToast({
						title: '请输入储值卡金额',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				const data = this.currentConfig
				data.shopId = this.shopId
				this.$request({
					method: 'post',
					url: '/applet/store/member/wallet/updateBalance',
					data,
					loading: true,
					isEncrypt: false
				}).then(res => {
					if (res.code === 200) {
						this.listData.forEach((item) => {
							if (item.userId === this.currentConfig.userId) {
								item.balance = this.currentConfig.balance
							}
						})
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						})
					}
					this.closePop()
				}).catch(err => {
					console.log('请求异常：', err)
				})
			},
			// 赠送时长卡
			sendCard(){
				const data = {
					shopId:this.shopId,
					userId:this.currentConfig.userId,
					giftDetailList:[]
				}
				this.timeCardList.forEach((item)=>{
					if(item.count > 0){
						const obj = {
							timeCardId:item.timeCardId,
							count:item.count
						}
						data.giftDetailList.push(obj)
					}
				})
				if (data.giftDetailList.length === 0) {
					uni.showToast({
						title: '请输入赠送时长卡的数量',
						duration: 2000,
						icon: 'none'
					})
					return
				}

				this.$request({
					method: 'post',
					url: '/applet/store/timeCard/gift',
					data,
					loading: true,
					isEncrypt: false
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: '时长卡已赠送',
							duration: 2000,
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						})
					}
					this.closePop()
				}).catch(err => {
					console.log('请求异常：', err)
				})
			},
			// 客户电话
			callNumber(item) {
				if (item.mobile && !this.isCheck) {
					//  #ifdef  H5
					// 为了兼容不同浏览器，使用encodeURIComponent进行编码
					const encodedPhoneNumber = encodeURIComponent(item.mobile);
					// 使用href设置电话链接
					window.location.href = `tel:${encodedPhoneNumber}`;
					//  #endif

					//  #ifdef MP-WEIXIN
					uni.makePhoneCall({
						phoneNumber: item.mobile
					})
					//  #endif
				}
			},

			// 搜索
			searchEvent() {
				this.pageNum = 1
				this.listData = []
				this.getUserList()
			},
			// 滚动加载
			getDataEvent() {
				if (this.listData.length < this.total) {
					this.pageNum++
					this.getUserList()
				}
			},
			// 获取用户列表
			getUserList() {
				const data = {
					shopId: this.shopId,
					keyword: this.searchVal,
					pageSize: this.pageSize,
					pageNum: this.pageNum
				}
				this.$request({
					method: 'post',
					url: '/applet/store/user/list',
					data,
					loading: true,
					isEncrypt: false
				}).then(res => {
					if (res.rows?.length > 0) {
						this.listData = [...this.listData, ...res.rows]
					}
					this.total = res.total
				}).catch(err => {
					console.log('请求异常：', err)
				})
			},
			// 获取时长卡列表
			getTimeCardList() {
				const data = {
					shopId: this.shopId
				}
				this.$request({
					method: 'post',
					url: '/applet/store/timeCard/list',
					data,
					loading: true,
					isEncrypt: false
				}).then(res => {
					this.timeCardList = res.rows || []
					this.timeCardList.forEach((item) => {
						item.count = 0
					})
				}).catch(err => {
					console.log('请求异常：', err)
				})
			},
		},
		onLoad(options) {
			this.shopId = options.shopId
			if(options?.isCheck === 'true'){
				this.isCheck = true
			}
			this.getUserList()
			this.getTimeCardList()
		}
	}
</script>

<style lang="scss" scoped>
	.user-list {
		
		.flex{
			display: flex;
		}

		.flex-box {
			display: flex;
			flex-wrap: wrap;
			
			.mr-box{
				margin-right: 15rpx;
			}
		}

		.flex-sb {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.header-box {
			background-color: #FFF;
			display: flex;
			padding: 10rpx 20rpx;
			align-items: center;
			font-size: 28rpx;
		}

		.scroll-box {
			height: calc(100vh - 184rpx);
		}

		.main {
			padding: 20rpx;
			background: #FFF;
		}

		.card-box {
			background: #FFF;
			border: 1px solid #EEE;
			border-radius: 20rpx;
			padding: 20rpx;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
		}

		.user-img {
			flex: 0 0 100rpx;
			height: 100rpx;
			border-radius: 50%;
			flex-shrink: 0;
			margin-right: 20rpx;
		}

		.card-title {
			font-weight: bold;
			font-size: 30rpx;
			color: #FF9600;
		}

		.card-text {
			color: #333;
			font-size: 26rpx;
			margin-top: 20rpx;
		}

		.mlr {
			margin: 0 20rpx;
		}

		.noMore {
			text-align: center;
			padding: 32rpx 0;
			color: #CCC;
			font-size: 28rpx;
		}

		.common-btn {
			border: 1px solid #333;
			color: #333;
			padding: 4rpx 20rpx;
			font-size: 26rpx;
			margin-left: 40rpx;
			border-radius: 10rpx;
			background: #ff9600;
			color: #FFF;
			border: none;
		}


		.search-btn {
			margin-left: 20rpx;

			.btn {
				color: #FFF;
				background: #ff9600;
				border-radius: 10rpx;
				padding: 16rpx 40rpx;
			}
		}

		.pop-box {
			background: #FFF;
			border-radius: 20rpx;
			padding: 30rpx;
			box-sizing: border-box;
			width: 730rpx;

			.pop-content {
				max-height: 800rpx;
				overflow-y: auto;
			}

			.pop-title {
				font-size: 32rpx;
				font-weight: 600;
				text-align: center;
				margin-bottom: 30rpx;
			}

			.pop-item-title-long {
				width: 240rpx;
				text-align: right;
			}

			.pop-item-title {
				width: 140rpx;
				text-align: right;
			}

			.pop-item {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				margin-bottom: 30rpx;
			}

			.pop-unit {
				margin-left: 10rpx;
			}

			.pop-btn-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 60rpx;

				.cancel-btn {
					padding: 8rpx 36rpx;
					font-size: 24rpx;
					border-radius: 10rpx;
					border: 1px solid #CCC;
				}

				.submit-btn {
					padding: 8rpx 36rpx;
					font-size: 24rpx;
					border-radius: 10rpx;
					color: #FFF;
					background: #ff9600;
				}
			}
		}

		.time-card-box {
			max-height: 800rpx;
			overflow-y: auto;

			.time-card {
				border: 1px solid #EEE;
				border-radius: 10rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
			}

			.time-card-item {
				margin-bottom: 10rpx;
			}
		}

	}
</style>